
#import "UDMOctogris_LevelView.h"
#import <AudioUnit/AudioUnit.h>
#import "CommonSettings.h"

#define minLevel (-60)
#define maxLevel (1)

@implementation UDMOctogris_LevelView

- (id)initWithFrame:(NSRect)frame
{
    if ((self = [super initWithFrame:frame]))
	{
        mLevel = minLevel;
    }
    return self;
}

- (void)drawRect:(NSRect)rect
{
    rect = [self bounds];
	
	[[NSColor blackColor] set];
	[NSBezierPath fillRect:rect];
	
	NSRect r2 = rect;
	r2.size.width *= (mLevel - minLevel) / (maxLevel - minLevel);
	
	const float yellowStart = -6;
	float hue;
	if (mLevel > 0) hue = 0;
	else if (mLevel < yellowStart) hue = 1 / 3.f;
	else
	{
		float p = (mLevel - yellowStart) / (-yellowStart); // 0 .. 1
		hue = (1 - p) / 3.f;
	}
	
	[[NSColor colorWithCalibratedHue:hue
				saturation:1
				brightness:1
				alpha:1] set];

	[NSBezierPath fillRect:r2];
	
	
	/*
	const float yellowStart = -1;
	const float redStart = 0;
	
	// green part
	{
		float level = (mLevel > yellowStart) ? yellowStart : mLevel;
		
		NSRect r2 = rect;
		r2.size.width *= (level - minLevel) / (maxLevel - minLevel);
		[[NSColor greenColor] set];
		[NSBezierPath fillRect:r2];
	}
	
	// yellow part
	if (mLevel > yellowStart)
	{
		float level = (mLevel > redStart) ? redStart : mLevel;
		
		NSRect r2 = rect;
		r2.origin.x += r2.size.width * (yellowStart - minLevel) / (maxLevel - minLevel);
		r2.size.width *= (level - minLevel) / (maxLevel - minLevel);
		[[NSColor yellowColor] set];
		[NSBezierPath fillRect:r2];
	}
	
	// red part
	if (mLevel > redStart)
	{
		NSRect r2 = rect;
		r2.origin.x += r2.size.width * (redStart - minLevel) / (maxLevel - minLevel);
		r2.size.width *= (mLevel - minLevel) / (maxLevel - minLevel);
		[[NSColor redColor] set];
		[NSBezierPath fillRect:r2];
	}
	*/
	
	[[NSColor grayColor] set];
	[NSBezierPath strokeRect:rect];
	
}

- (void) setLevel:(float)level
{
	mLevel = linearToDb(level);
	
	if (mLevel < minLevel) mLevel = minLevel;
	else if (mLevel > maxLevel) mLevel = maxLevel;
	
	[self setNeedsDisplay:YES];
}

@end
